package com.zx.my.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zx.my.dao.MyStudyMapper;
import com.zx.my.entity.MyStudy;
import com.zx.my.model.StudyChartDto;
import com.zx.util.Constants;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Slf4j
@Service
public class MyStudyService {

    @Autowired
    private MyStudyMapper myStudyMapper;

    public List<MyStudy> getByUserId(int userId) {
        log.info("MyStudyService#getByUserId userId={}", userId);
        List<MyStudy> queryData = this.myStudyMapper.selectList(Wrappers.
                <MyStudy>lambdaQuery()
                .eq(MyStudy::getUserId, userId)
                .orderByDesc(MyStudy::getBeginTime)
                .last("limit 20")
        );
        this.fillStatus(queryData);
        return queryData;
    }

    public List<MyStudy> getRunByUserId(int userId) {
        log.info("MyStudyService#getByUserId userId={}", userId);
        List<MyStudy> queryData = this.myStudyMapper.selectList(Wrappers.
                <MyStudy>lambdaQuery()
                .eq(MyStudy::getUserId, userId)
                .eq(MyStudy::getStudyStatus, Constants.MY_STUDY_RUN)
                .orderByAsc(MyStudy::getBeginTime));
        this.fillStatus(queryData);
        return queryData;
    }


    private void fillStatus(List<MyStudy> li) {
        li.forEach(x -> {
            if (x.getStudyStatus() == Constants.MY_STUDY_FINISH) {
                x.setStudyStatusStr("完成");
            } else {
                x.setStudyStatusStr("进行中完成");
            }
            Integer studyTime = x.getStudyTime();
            int hour = studyTime / (60 * 60);
            int minute = (studyTime - hour * 60 * 60) / 60;
            int second = (studyTime - hour * 60 * 60 - minute * 60);
            String time = String.format("%s:%s:%s",
                    hour, minute, second
            );
            x.setStudyTimeStr(time);
        });

    }

    public boolean save(MyStudy myStudy) {
        log.info("MyStudyService#save myStudy={}", myStudy);
        return this.myStudyMapper.insert(myStudy) > 0;
    }

    public boolean finish(int id) {
        log.info("MyStudyService#finish id={}", id);
        MyStudy study = this.myStudyMapper.selectById(id);
        if (study == null) {
            return false;
        }
        Date now = new Date();
        study
                .setEndTime(now)
                .setStudyTime((int) (now.getTime() - study.getBeginTime().getTime()) / 1000)
                .setStudyStatus(Constants.MY_STUDY_FINISH);
        return this.myStudyMapper.updateById(study) > 0;
    }

    public List<StudyChartDto> getChart(Date begin, Date end, int type) {
        log.info("MyStudyService#getChart");
        begin = DateUtil.beginOfDay(begin);
        end = DateUtil.endOfDay(end);
        List<DateTime> timeList = null;
        // 生成模板表
        List<StudyChartDto> templates = null;
        // 查询的数据
        List<StudyChartDto> queryData = null;
        if (type == 1) {
            timeList = DateUtil.rangeToList(begin, end, DateField.DAY_OF_YEAR);
            templates = timeList.stream()
                    .map(x -> new StudyChartDto().setDate(DateUtil.format(x, Constants.DATE_FORMAT_4)).setTime(0))
                    .collect(Collectors.toList());
            queryData = this.myStudyMapper.getDayChart(begin, end);
        } else if (type == 2) {
            timeList = DateUtil.rangeToList(begin, end, DateField.MONTH);
            templates = timeList.stream()
                    .map(x -> new StudyChartDto().setDate(DateUtil.format(x, Constants.DATE_FORMAT_5)).setTime(0))
                    .collect(Collectors.toList());
            queryData = this.myStudyMapper.getMonthChart(begin, end);
        }

        if (!CollectionUtils.isEmpty(queryData)) {
            Map<String, List<StudyChartDto>> map = queryData.stream()
                    .collect(Collectors.groupingBy(StudyChartDto::getDate));
            for (StudyChartDto dto : templates) {
                List<StudyChartDto> list = map.get(dto.getDate());
                if (list != null) {
                    double time = list.get(0).getTime();
                    dto.setTime(time);
                }
            }
        }

        return templates;
    }

}
